package org.wevil.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * properties文件工具类
 */
public class PropertiesUtil {

    // 配置对象
    Configuration config = null;
    // 配置文件位置
    String config_path = "";

    /**
     * 构造方法。
     *
     * @param config_path 配置文件名称，如： xxx.properties
     */
    public PropertiesUtil(String config_path) {
        try {
            this.config_path = config_path;
            config = new PropertiesConfiguration(config_path);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取配置文件里的value
     *
     * @param key key值
     */
    public String getValue(String key) {
        return config.getString(key);
    }

    /**
     * 修改value的值
     *
     * @param key   key值
     * @param value 要修改的vlaue值
     */
    public boolean setValue(String key, String value) throws IOException {
        File f = new File(config_path);
        boolean res = false;
        if (f.exists()) {
            BufferedReader br = new BufferedReader(new FileReader(f));
            String outstr = "";
            String line = "";
            while ((line = br.readLine()) != null) {
                if (line.equals("")) //如果为空
                {
                    outstr += "\n";
                    continue;
                }
                if (line.startsWith("#")) //如果为注释
                {
                    outstr += line + "\n";
                    continue;
                }
                if (line.trim().startsWith(key)) {
                    String[] keyandvalue = line.split("=");
                    outstr += keyandvalue[0].toString() + "= " + value.toString() + "\n";
                    res = true;
                    continue;
                }
                outstr += line + "\n";
            }
            if (res) {

                FileWriter fw = new FileWriter(config_path, false);
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(outstr);
                bw.close();
                fw.close();
                return true;
            }
        }
        return false;
    }
}
